@file:OptIn(ExperimentalStdlibApi::class)

package com.harth.flutter_ns_ble

import android.util.Log
import no.nordicsemi.android.ble.data.Data
import no.nordicsemi.android.ble.data.DataMerger
import no.nordicsemi.android.ble.data.DataStream
import java.nio.ByteBuffer
import java.nio.IntBuffer

class BlePacket(val cmd: Int, val length: Int, val sum: Int, val data: ByteArray?) {
    companion object Companion {
        fun fromByteArray(byteArray: ByteArray): BlePacket? {
            if (byteArray.size >= 6) {
                val data = Data(byteArray)
                if (data.getByte(0) == 0xbc.toByte()) {
                    val cmd = data.getIntValue(Data.FORMAT_UINT8, 1)
                    if (cmd != null) {
                        val bizData: ByteArray = byteArray.drop(6).toByteArray()
                        val dataLength = bizData.size
                        val length = data.getIntValue(Data.FORMAT_UINT16_LE, 2)
                        var dataSum = 0
                        dataSum = bizData.sumOf { it.toInt() and 0xff }
                        val sum = data.getIntValue(Data.FORMAT_UINT16_LE, 4)
                        if (dataLength == length) {
                            if (dataSum == sum) {
                                return BlePacket(
                                    cmd = cmd,
                                    length = length,
                                    sum = sum,
                                    data = bizData
                                )
                            } else {
                                Log.e(
                                    "BlePacket",
                                    "数据校验错误, 期望:${
                                        byteArray.copyOfRange(4, 6).toHexString()
                                    },$sum 实际:$dataSum"
                                );
                            }
                        } else {
                            Log.e(
                                "BlePacket",
                                "数据长度错误, 期望:$length 实际:$dataLength,${bizData.toHexString()}"
                            );
                        }
                    }

                } else {
                    Log.e("BlePacket", "第一个字节必须是0xBC");
                }
            }else{
                Log.e("BlePacket", "长度不够:${byteArray.size},${byteArray.toHexString()}")
            }

            return null
        }

        fun fromCmd(cmd: Int, data: ByteArray?): BlePacket {
            val length = data?.size ?: 0
            val sum = data?.sumOf { it.toInt() and 0xff } ?: 0

            return BlePacket(
                cmd = cmd,
                length = length,
                sum = sum,
                data = data
            )
        }
    }


    val byteArray: ByteArray
        get() {
            var list = byteArrayOf(0xbc.toByte(), cmd.toByte())
            list += length.toByteArray
            list += sum.toByteArray
            data?.let { list += it }
            Log.e("BlePacket", "byteArray:${length.toByteArray.toHexString()},${sum.toByteArray.toHexString()},${data?.toHexString()}")
            return list
        }

}

class BlePacketDataMerger: DataMerger {
    override fun merge(
        output: DataStream,
        lastPacket: ByteArray?,
        index: Int
    ): Boolean {
        lastPacket?.let { output.write(it) }
        return BlePacket.fromByteArray(output.toByteArray()) != null
    }
}

val Int.toByteArray: ByteArray
    get() {
        val intValue: Int = this
        val low16Bits: Int = intValue and 0xFFFF // 提取低16位
        val byteArray = ByteArray(2) // 创建一个包含两个字节的数组
        byteArray[0] = (low16Bits and 0xFF).toByte() // 提取低8位作为第一个字节
        byteArray[1] = (low16Bits shr 8 and 0xFF).toByte() // 右移8位后提取高8位作为第二个字节
        return byteArray
    }